#require 'fastercsv'
class ReportController < ApplicationController     
  before_filter :login_required  
  
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @report_pages, @reports = paginate :reports, :per_page => 10
  end

  def show  
    @report = Report.find(params[:id])             
    @report_input = params[:report_input] 
    @erb_query = nil
    @report_ouput = nil
    
    if @report_input and not @report_input.empty?
      @report_input = HashModel::Model.new(@report_input) 
      sql = ActiveRecord::Base.connection()
      @erb_query = render_to_string :inline =>@report.erb_query, 
                    :locals => {:@report_input => @report_input, :sql => sql} 
      @report_output = sql.select_all(@erb_query)   
      logger.info "#{@erb_query}" 
    end                                          
    
  end

  def new
    @report = Report.new
  end

  def create
    @report = Report.new(params[:report])
    if @report.save
      flash[:notice] = 'Report was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @report = Report.find(params[:id])
  end

  def update
    @report = Report.find(params[:id])
    if @report.update_attributes(params[:report])
      flash[:notice] = 'Report was successfully updated.'
      redirect_to :action => 'show', :id => @report
    else
      render :action => 'edit'
    end  
    
  end

  def destroy    
    if current_user.is_admin?
      Report.find(params[:id]).destroy
    end
    redirect_to :action => 'list'
  end              
  
end
